var mainCustomerId = sessionStorage.getItem('mainCustomerId') //主客户id
var operateUserId = JSON.parse(decodeURIComponent(web.readCookie('loginData')))
    .user.user_ID
var operateUserName = JSON.parse(
    decodeURIComponent(web.readCookie('loginData'))
).user.name
var popDataSource = []
//获取接口数据
var getData = {
    // 修改物料号查询
    findMaterielById: function () {
        var materielId = sessionStorage.getItem('materielId')
        //"materielId"为add代表是添加按钮跳转过来的
        var add = JSON.parse(materielId)
        if (add.materielId != 'add') {
            var params = {
                materielId: add.materielId,
            }
            $.ajax({
                url: root.member.findMaterielById,
                cache: false, //禁用缓存
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                data: JSON.stringify(params),
                success: function (data) {
                    if (data.errorCode == 0) {
                        renderData.showModifyData(data.data)
                    }
                    // $.Huimodalalert('选择成功',2000);
                },
                error: function (msg) {
                    $.Huimodalalert(msg, 2000)
                },
            })
        }
    },
    // 弹窗-- 获取弹窗正常商品查询接口
    listPageBySkuDimension: function () {
        var skuCode = $('#normalskucode').val() //鑫方盛SKU编码
        var skuName = $('#normalskuname').val() //鑫方盛SKU名称
        /* var productType = 10;//10 正常商品  20 临采商品*/
        var params = {
            mainCustomerId: mainCustomerId, //主客户id
            skuCode: skuCode, //商品编码
            skuName: skuName, //物料号
            pageNum: 1,
            pageSize: 50,
        }
        // 获取输入框的输入信息
        $.ajax({
            url: root.member.listPageBySkuDimension,
            cache: false, //禁用缓存
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(params),
            success: function (data) {
                if (data.errorCode == 0 && data.data.data.length > 0) {
                    renderData.popNormalDatas(data.data)
                    $('.M-box3').pagination({
                        pageCount: data.data.pageCount,
                        jump: true,
                        coping: true,
                        prevContent: '上页',
                        nextContent: '下页',
                        callback: function (api) {
                            params.pageNum = api.getCurrent()
                            $.ajax({
                                url: root.member.listPageBySkuDimension,
                                cache: false, //禁用缓存
                                type: 'POST',
                                dataType: 'json',
                                contentType: 'application/json',
                                data: JSON.stringify(params),
                                success: function (data) {
                                    if (data.errorCode == 0) {
                                        renderData.popNormalDatas(data.data)
                                    }
                                },
                                error: function (msg) {
                                    $.Huimodalalert('失败！', 2000)
                                },
                            })
                        },
                    })
                } else {
                    $('.M-box3').pagination({
                        pageCount: 0,
                    })
                    renderData.popNormalDatas(data.data)
                }
            },
            error: function (msg) {
                $.Huimodalalert(msg, 2000)
            },
        })
    },
    // 弹窗-- 获取弹窗临采商品查询接口
    queryTempPurchaseSkuList: function () {
        var skuCode = $('#tempskucode').val() //鑫方盛SKU编码
        var skuName = $('#tempskuname').val() //鑫方盛SKU名称
        var productType = '' //10 正常商品  20 临采商品
        var mainCustomerId = sessionStorage.getItem('mainCustomerId') //主客户id
        var params = {
            mainCustomerId: mainCustomerId, //主客户id
            skuCode: skuCode, //商品编码
            skuName: skuName, //物料号
            productType: productType, //10 正常商品  20 临采商品
            pageNum: 1,
            pageSize: 10,
        }
        // 获取输入框的输入信息
        $.ajax({
            url: root.member.queryTempPurchaseSkuList,
            cache: false, //禁用缓存
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(params),
            success: function (data) {
                if (data.errorCode == 0 && data.data.data.length > 0) {
                    renderData.popTempDatas(data.data)
                    $('.M-box4').pagination({
                        pageCount: data.data.pageCount,
                        jump: true,
                        coping: true,
                        prevContent: '上页',
                        nextContent: '下页',
                        callback: function (api) {
                            var params = {
                                //mainCustomerId: mainCustomerId,//主客户id
                                mainCustomerId: '2273',
                                skuCode: skuCode, //商品编码
                                skuName: skuName, //物料号
                                productType: productType, //10 正常商品  20 临采商品
                                pageNum: api.getCurrent(),
                                pageSize: 10,
                            }
                            $.ajax({
                                url: root.member.queryTempPurchaseSkuList,
                                cache: false, //禁用缓存
                                type: 'POST',
                                dataType: 'json',
                                contentType: 'application/json',
                                data: JSON.stringify(params),
                                success: function (data) {
                                    if (data.errorCode == 0) {
                                        renderData.popTempDatas(data.data)
                                    }
                                },
                                error: function (msg) {
                                    $.Huimodalalert('失败！', 2000)
                                },
                            })
                        },
                    })
                } else {
                    $('.M-box4').pagination({
                        pageCount: 0,
                    })
                    renderData.popTempDatas(data.data)
                }
            },
            error: function (msg) {
                $.Huimodalalert(msg, 2000)
            },
        })
    },
    //保存物料号
    saveMateriel: function (params) {
        $.ajax({
            url: root.member.saveMateriel,
            cache: false, //禁用缓存
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(params),
            success: function (data) {
                if (data.errorCode == 0) {
                    $.Huimodalalert('保存成功', 2000)
                    // 保存刷新页面展示数据信息
                    window.parent.location =
                        '../../../html/Customer/accountAystem/material_number.html?refresh=' +
                        1
                }
            },
            error: function (msg) {
                $.Huimodalalert(msg, 2000)
            },
        })
    },
    checkMateriel: function (skuCode) {
        var check_res = "";
        var json = {
            mainCustomerId: mainCustomerId,
            skuCode: skuCode,
        }
        $.ajax({
            url: root.member.checkMateriel,
            cache: false, //禁用缓存
            async: false,
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(json),
            success: function (data) {
                if (data.errorCode == 0) {
                    check_res = data.data;
                } else {
                    $.Huimodalalert(data.msg, 2000);
                    return false;
                }
            },
            error: function (msg) {
                $.Huimodalalert(msg, 2000);
                return false;
            }
        })
        return check_res;
    }
}
// 渲染数据
var renderData = {
    // 修改数据回显
    showModifyData: function (data) {
        //鑫方盛SKU编码
        var skuCode = $('#skuCode')
        //客户物料号
        var materielNumber = $('#materielNumber')
        //客户计量单位
        var unitName = $('#unitName')
        $('#materielName').val(data.materielName) //客户物料名称：
        /*  设置默认值 */
        skuCode.val(data.skuCode)
        materielNumber.val(data.materielNumber)
        unitName.val(data.unitName)
        $("input[name='materielId']").val(data.materielId)
    },
    //正常商品查询接口
    popNormalDatas: function (data) {
        popDataSource = []
        if (data != null && data != '') {
            var startRow = data.startRow + 1
            $.each(data.data, function (index, item) {
                var dataT = startRow++
                var obj = {}
                obj.skuCode = item.skuCode //临采sku编码
                obj.skuName = item.skuName //临采sku名称
                obj.unitName = item.unitName //临采sku单位
                obj.updateIds = item.updateIds // 选择添加的id
                obj.dataT = dataT
                obj.productType = 10 // 正常商品标识
                popDataSource.push(obj)
            })
        }
        renderData.renderNoramlPopDatas(popDataSource)
    },
    // 弹窗正常数据渲染数据渲染
    renderNoramlPopDatas: function (data) {
        var datatable = $('#popnormallists').dataTable() // 初始化dataTable，清空上一个值
        datatable.fnClearTable() //清空一下table
        datatable.fnDestroy() //还原初始化了的datatable
        $('#popnormallists').DataTable({
            order: [[1, 'desc']],
            autoWidth: false,
            ordering: false,
            searching: false,
            paging: false,
            retrieve: true,
            destroy: true,
            bAutoWidth: true,
            bLengthChange: true,
            aLengthMenu: [5, 10, 25, 50],
            oLanguage: {
                sLengthMenu: '每页显示 _MENU_ 条记录',
                sZeroRecords: '抱歉， 没有找到',
                sInfo: '从 _START_ 到 _END_ /共 _TOTAL_ 条数据',
                sInfoEmpty: '',
                sInfoFiltered: '(从 _MAX_ 条数据中检索)',
                oPaginate: {
                    sFirst: '首页',
                    sPrevious: '前一页',
                    sNext: '后一页',
                    sLast: '尾页',
                },
                sZeroRecords: '没有检索到数据',
                /* "sProcessing": "<img src='./loading.gif' />",*/
            },
            data: data,
            columnDefs: [
                {
                    visible: true,
                    targets: 0,
                },
                {
                    render: function (data, type, row, meta) {
                        var skuCode = row.skuCode
                        if (skuCode == undefined) {
                            skuCode = ''
                        }
                        return (
                            '<span style="text-align: center;" >' +
                            skuCode +
                            '</span>'
                        )
                    },
                    targets: 0,
                },
                {
                    render: function (data, type, row, meta) {
                        var skuName = row.skuName
                        if (skuName == undefined) {
                            skuName = ''
                        }
                        return (
                            '<span style="text-align: center;" >' +
                            skuName +
                            '</span>'
                        )
                    },
                    targets: 1,
                },
                {
                    render: function (data, type, row, meta) {
                        var unitName = row.unitName
                        if (unitName == undefined) {
                            unitName = ''
                        }
                        return (
                            '<span style="text-align: center;">' +
                            unitName +
                            '</span>'
                        )
                    },
                    targets: 2,
                },
                {
                    render: function (data, type, row, meta) {
                        var select =
                            '<span style="text-align: center; color: blue;cursor: pointer" onclick="normalSelect(\'' +
                            row.skuCode +
                            "','" +
                            row.productType +
                            '\')">' +
                            '选择' +
                            '</span>'
                        return select
                    },
                    targets: 3,
                },
            ],
        })
    },
    //临采商品查询接口
    popTempDatas: function (data) {
        popDataSource = []
        if (data != null && data != '') {
            var startRow = data.startRow + 1
            $.each(data.data, function (index, item) {
                var dataT = startRow++
                var obj = {}
                obj.skuCode = item.skuCode //临采sku编码
                obj.oldSkuName = item.oldSkuName //临采sku名称
                obj.unit = item.unit //临采sku单位
                obj.updateIds = item.updateIds // 选择添加的id
                obj.dataT = dataT
                obj.productType = 20 // 临采商品标识
                popDataSource.push(obj)
            })
        }
        renderData.renderTempPopDatas(popDataSource)
    },
    // 弹窗临采数据渲染
    renderTempPopDatas: function (data) {
        var datatable = $('#popTemporaylists').dataTable() // 初始化dataTable，清空上一个值
        datatable.fnClearTable() //清空一下table
        datatable.fnDestroy() //还原初始化了的datatable
        $('#popTemporaylists').DataTable({
            order: [[1, 'desc']],
            autoWidth: false,
            ordering: false,
            searching: false,
            paging: false,
            retrieve: true,
            destroy: true,
            bAutoWidth: true,
            bLengthChange: true,
            aLengthMenu: [5, 10, 25, 50],
            oLanguage: {
                sLengthMenu: '每页显示 _MENU_ 条记录',
                sZeroRecords: '抱歉， 没有找到',
                sInfo: '从 _START_ 到 _END_ /共 _TOTAL_ 条数据',
                sInfoEmpty: '',
                sInfoFiltered: '(从 _MAX_ 条数据中检索)',
                oPaginate: {
                    sFirst: '首页',
                    sPrevious: '前一页',
                    sNext: '后一页',
                    sLast: '尾页',
                },
                sZeroRecords: '没有检索到数据',
                /* "sProcessing": "<img src='./loading.gif' />",*/
            },
            data: data,
            columnDefs: [
                {
                    visible: true,
                    targets: 0,
                },
                {
                    render: function (data, type, row, meta) {
                        var skuCode = row.skuCode
                        if (skuCode == undefined) {
                            skuCode = ''
                        }
                        return (
                            '<span style="text-align: center;" >' +
                            skuCode +
                            '</span>'
                        )
                    },
                    targets: 0,
                },
                {
                    render: function (data, type, row, meta) {
                        var oldSkuName = row.oldSkuName
                        if (oldSkuName == undefined) {
                            oldSkuName = ''
                        }
                        return (
                            '<span style="text-align: center;" >' +
                            oldSkuName +
                            '</span>'
                        )
                    },
                    targets: 1,
                },
                {
                    render: function (data, type, row, meta) {
                        var unit = row.unit
                        if (unit == undefined) {
                            unit = ''
                        }
                        return (
                            '<span style="text-align: center;">' +
                            unit +
                            '</span>'
                        )
                    },
                    targets: 2,
                },
                {
                    render: function (data, type, row, meta) {
                        var select =
                            '<span style="text-align: center; color: blue;cursor: pointer" onclick="tempSelect(\'' +
                            row.skuCode +
                            "','" +
                            row.productType +
                            '\')">' +
                            '选择' +
                            '</span>'
                        return select
                    },
                    targets: 3,
                },
            ],
        })
    },
}
getData.findMaterielById()
/*   start  正常商品池相关信息  */

// 选择正常商品池--按钮
function selectNormalProduct () {
    $('#normal').modal('show')
    $('#temp').modal('hide')
    $('#normalskucode').val('')
    $('#normalskuname').val('')
    var datatable = $('#popnormallists').dataTable() // 初始化dataTable，清空上一个值
    datatable.fnClearTable() //清空一下table
    datatable.fnDestroy() //还原初始化了的datatable
    $('.M-box3').pagination({
        pageCount: 0,
    })
}

// 点击弹窗正常商品查询按钮
function popNormalSearch () {
    getData.listPageBySkuDimension()
}

// 正常商品 弹窗选择
function normalSelect (skuCode, productType) {
    $('#skuCode').val(skuCode)
    // 存储临采商品标识 10
    sessionStorage.setItem('productType', productType)
    $('#temp').modal('hide')
    $('#normal').modal('hide')
}
/*   end  正常商品池相关信息结束   */

/*   start  临采商品池相关信息  */

// 选择临采商品池--按钮
function selectTempProduct () {
    $('#temp').modal('show')
    $('#normal').modal('hide')
    $('#tempskucode').val('')
    $('#tempskuname').val('')
    var datatable = $('#popTemporaylists').dataTable() // 初始化dataTable，清空上一个值
    datatable.fnClearTable() //清空一下table
    datatable.fnDestroy() //还原初始化了的datatable
    $('.M-box4').pagination({
        pageCount: 0,
    })
}
function popTempSearch () {
    getData.queryTempPurchaseSkuList()
}
// 临采商品弹窗选择
function tempSelect (skuCode, productType) {
    $('#skuCode').val(skuCode)
    // 存储临采商品标识 20
    sessionStorage.setItem('productType', productType)
    $('#temp').modal('hide')
    $('#normal').modal('hide')
}
/*  end  临采商品池相关信息结束  */

// 保存按钮
function saveData () {
    // 校验输入框信息
    var skuCode = $('#skuCode').val()
    var materielNumber = $('#materielNumber').val()
    var unitName = $('#unitName').val()
    var materielName = $('#materielName').val() //客户物料名称：
    var materielId = $("input[name='materielId']").val()
    if (skuCode == '') {
        $.Huimodalalert('请选择鑫方盛SKU编码', 2000)
        return
    }
    if (materielNumber == '') {
        $.Huimodalalert('请输入客户物料号', 2000)
        return
    }
    if (unitName == '') {
        $.Huimodalalert('请输入客户计量单位', 2000)
        return
    }
    if (materielName == '') {
        $.Huimodalalert('请输入客户物料名称', 2000)
        return
    }

    // 保存获取商品池标识 10 是正常商品 20 是临采商品
    var productType = sessionStorage.getItem('productType')
    var params = {
        materielId: materielId,
        mainCustomerId: sessionStorage.getItem('mainCustomerId'), //主客户id
        materielNumber: $('#materielNumber').val(),
        unitName: $('#unitName').val(),
        materielName: materielName,
        skuCode: $('#skuCode').val(),
        productType: productType,
        operateUserId: operateUserId,
        operateUserName: operateUserName,
    }
    console.log(params);
    //主键为空为新增，校验sku是否重复
    if (materielId == null || materielId == '') {
        var check_M = getData.checkMateriel(skuCode);
        if (check_M > 0) {
            layer.confirm(
                '鑫方盛SKU编码重复,是否覆盖',
                {
                    btn: ['确认', '取消'],
                    title: '提示',
                    offset: 't',
                },
                function (index) {
                    layer.close(index);
                    getData.saveMateriel(params);
                },
                function (index, layero) {
                    layer.close(index);
                }
            )
        } else {
            getData.saveMateriel(params);
        }
    } else {
        getData.saveMateriel(params);
    }
}


